package com.scalar.chiptrack.adaptor.costcode;

import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.ScalarException;

import java.io.File;
import java.util.ArrayList;

import jxl.Workbook;
import jxl.Cell;
import jxl.Sheet;
import jxl.CellType;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Mar 23, 2007
 * Time: 5:25:05 PM
 */
public class CostCodeParser extends JobHandler implements AdaptorConstants
{


    private String filePath = null;
    private Logger m_parserLogger = null;
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    public CostCodeParser() throws ScalarException
    {
        String logDirectory;
        String logFileName = "cost_code_parser%u.log";
        String logPrefix = "cost_code_Parser";
        String level = "debug";
        int maxFileSize = 4096 * 500;
        int fileCount = 1;

        filePath = ConfigManager.getCostCodesSheetDirectory();
        logDirectory = new File(filePath).getParent();
        try
        {
            m_parserLogger = new Logger(logDirectory, logFileName, logPrefix, level, maxFileSize, fileCount);
            InventoryLotDAO.setLogger(m_parserLogger);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception
    {
        new CostCodeParser().execute();
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        printVersionInfo();

        boolean success = true;
        ArrayList costCodesList = new ArrayList();
        costCodesList = parseClassCodesheet(filePath);

        try
        {

            if( costCodesList != null && costCodesList.size() > 0 )
            {
                  AdaptorDAO.saveCostCodes( costCodesList.iterator() );
            }
        }
        catch( ScalarException se )
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Die Bank Lot information into database: " + se );
            throw se;
        }

        if( success == true )
        {
            System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
        }
    }

    /**
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    private ArrayList parseClassCodesheet(String fileName) throws Exception
    {
        ArrayList costCodesList = new ArrayList();
        CostCodeStatus costCodeStatus = null;
        String checkValue = null;

        if (fileName == null)
        {
            throw new ScalarException("Filename argument is null");
        }

        try
        {

            File wipStatusFile = new File(fileName);

            if (wipStatusFile.exists() == false)
            {
                throw new ScalarException(fileName + " doesnt exist");
            }

            log("\nFound " + fileName);
            log("Parsing the file for Cost Codes Report...");
            System.out.println("\nFound " + fileName);
            System.out.println("Parsing the file for Cost Codes Report...");

            Workbook workbook = Workbook.getWorkbook(wipStatusFile);

            Sheet sheet = workbook.getSheet("classcodes");

            Cell[] row = null;

            for (int rowCount = 4; rowCount < sheet.getRows(); rowCount++)
            {
                row = sheet.getRow(rowCount);

                costCodeStatus = new CostCodeStatus();

                if ( row != null && row.length > 50 )
                {
                    checkValue = row[17].getContents().trim();

                    if (checkValue != null && checkValue.trim().length() > 0)
                    {
                        if (row.length > 17)
                        {
                            if (row[17].getType().equals(CellType.EMPTY))
                            {
                                costCodeStatus.setCost(null);
                            }
                            else
                            {
                                costCodeStatus.setCost(row[17].getContents().trim());
                            }
                        }
                        if (row.length > 20)
                        {
                            if (row[20].getType().equals(CellType.EMPTY))
                            {
                                costCodeStatus.setMktPartNumber(null);
                            }
                            else
                            {
                                costCodeStatus.setMktPartNumber(row[20].getContents().trim());
                            }
                        }
                        if (costCodeStatus.getCost() != null && costCodeStatus.getMktPartNumber() != null && !"1".equalsIgnoreCase(costCodeStatus.getMktPartNumber()) && !"2".equalsIgnoreCase(costCodeStatus.getMktPartNumber()))
                        {
                            costCodesList.add(costCodeStatus);
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new ScalarException("Exception " + e);
        }

        return costCodesList;
    }


    private void printVersionInfo()
    {
        String info = "\n\n+----------- Running Cost Codes Parser on " + new java.util.Date(System.currentTimeMillis()) + " -------------+\n" +
                "\n+---------------------------------------------------------------+\n" +
                "+                                                                \n" +
                "+           Class Cost Data Interpreter - Beta          \n" +
                "+                                                                \n" +
                "+    Copy Right (C) 2007 - ScalarSoft Inc., All rights reserved.  \n" +
                "+                                                                \n" +
                "+---------------------------------------------------------------+\n";
        System.out.println(info);
        log(info);
    } //end of printVersionInfo

    /**
     *
     * @param message
     */
    private void log(String message)
    {

        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}
